Imports System.Data.SqlClient
Imports System.Web.Security
Imports System.Data

Partial Class Map
    Inherits System.Web.UI.Page

    Private conn As SqlConnection
    Private cmd As SqlCommand

    ''' <summary>
    ''' Connecto to the database
    ''' </summary>
    ''' <remarks></remarks>
    Protected Sub connect()

        Try
            Dim connectionString As String = ConfigurationManager.ConnectionStrings("mydb").ConnectionString

            conn = New SqlConnection(connectionString)
            conn.Open()

            ' Execute command and fetch pwd field into lookupPassword string.
            'lookupPassword = cmd.ExecuteScalar()
        Catch ex As Exception
            ' Add error handling here for debugging.
            ' This error message should not be sent back to the caller.
            System.Diagnostics.Trace.WriteLine("[Connection] Exception " & ex.Message)
        End Try
    End Sub

    ''' <summary>
    ''' Disconnects from the database
    ''' </summary>
    ''' <remarks></remarks>
    Private Sub disconnect()
        ' Cleanup command and connection objects.
        cmd.Dispose()
        conn.Dispose()
    End Sub

    ''' <summary>
    ''' Get the current logged-in user
    ''' </summary>
    ''' <returns></returns>
    ''' <remarks></remarks>
    Protected Function getAuthorizedUser() As String
        Return HttpContext.Current.User.Identity.Name
    End Function

    ''' <summary>
    ''' Get the current logged-in user's group
    ''' </summary>
    ''' <returns></returns>
    ''' <remarks></remarks>
    Protected Function getGroup() As String
        'Take from the cookie the actual name of the user
        Dim currentUser As String = getAuthorizedUser()

        Dim currentGroup As String

        connect()
        cmd = New SqlCommand("Select FK_groups from Users where uname = @currentUser", conn)
        cmd.Parameters.Add("@currentUser", SqlDbType.VarChar, 50)
        cmd.Parameters("@currentUser").Value = currentUser
        currentGroup = cmd.ExecuteScalar()
        disconnect()

        Return currentGroup
    End Function

    ''' <summary>
    ''' Get all the users in the current logged-in user's group
    ''' </summary>
    ''' <returns>Users in the group</returns>
    ''' <remarks></remarks>
    Protected Function getUsers() As ArrayList
        Dim currentGroup As String = getGroup()
        Dim reader As SqlDataReader
        Dim users As New ArrayList()

        connect()
        cmd = New SqlCommand("Select uname, color from Users where FK_groups = @currentGroup and userRole = 'User' ", conn)
        cmd.Parameters.Add("@currentGroup", SqlDbType.VarChar, 50)
        cmd.Parameters("@currentGroup").Value = currentGroup
        reader = cmd.ExecuteReader()
        While (reader.Read())
            Dim user(2) As String
            user(0) = "" & reader.GetString(0)  'name
            user(1) = "" & reader.GetString(1)  'color
            users.Add(user)
        End While
        disconnect()

        Return users
    End Function

    ''' <summary>
    ''' Get the coordinates of a user
    ''' </summary>
    ''' <param name="user"></param>
    ''' <returns>JS piece of code to draw in GMaps a line</returns>
    ''' <remarks></remarks>
    Protected Function getCoordinates(ByVal user As String) As String
        Dim resultLine As String = ""
        Dim reader As SqlDataReader

        connect()
        cmd = New SqlCommand("Select latitude, longitude from Coordinates where FK_user = @currentUser", conn)
        cmd.Parameters.Add("@currentUser", SqlDbType.VarChar, 50)
        cmd.Parameters("@currentUser").Value = user
        reader = cmd.ExecuteReader()
        While (reader.Read())
            resultLine += "new GLatLng(" & reader.GetString(0) & ", " & reader.GetString(1) & "),"
        End While
        disconnect()
        If (resultLine.Length >= 1) Then
            resultLine = resultLine.Substring(0, resultLine.Length - 1)
        End If
        Return resultLine
    End Function

    ''' <summary>
    ''' Get the actual coordinate of a user to draw a marker on Gmap
    ''' </summary>
    ''' <param name="user"></param>
    ''' <returns>Coordinate for the marker of the given user</returns>
    ''' <remarks></remarks>
    Protected Function getActualCoordinate(ByVal user As String) As String
        Dim resultCode As String = "0,0"
        Dim reader As SqlDataReader

        connect()
        cmd = New SqlCommand("Select latitude, longitude from Coordinates where FK_user = @currentUser order by id desc", conn)
        cmd.Parameters.Add("@currentUser", SqlDbType.VarChar, 50)
        cmd.Parameters("@currentUser").Value = user
        reader = cmd.ExecuteReader()
        While (reader.Read())
            resultCode = reader.GetString(0) & ", " & reader.GetString(1)
            Exit While
        End While
        disconnect()

        Return resultCode
    End Function

    ''' <summary>
    ''' Get the marker of a given user
    ''' </summary>
    ''' <param name="user"></param>
    ''' <returns>JS code do draw a marker on Gmap</returns>
    ''' <remarks></remarks>
    Protected Function getMarker(ByVal user As String) As String
        Return "new GLatLng(" & getActualCoordinate(user) & ")"
    End Function

    ''' <summary>
    ''' Generates the code needed to draw all the lines of the users
    ''' </summary>
    ''' <returns>JS code to draw users' lines</returns>
    ''' <remarks></remarks>
    Protected Function printGPolylines() As String
        Dim resultCode As String = ""
        Dim users As ArrayList = getUsers()
        Dim tempCoordinates As String

        Dim en As IEnumerator = users.GetEnumerator
        While en.MoveNext ''For each user print his line
            tempCoordinates = getCoordinates(en.Current(0))
            If (tempCoordinates.Length > 0) Then
                resultCode += "var polyline" & en.Current(0) & " = new GPolyline(["
                resultCode += tempCoordinates
                resultCode += "]," & Chr(34) & en.Current(1) & Chr(34) & ", 5); map.addOverlay(polyline" & en.Current(0) & ");"
            End If
        End While

        Return resultCode
    End Function

    ''' <summary>
    ''' Generates the code needed to draw all the markers of the users' actual position
    ''' </summary>
    ''' <returns>JS code to draw users' markers</returns>
    ''' <remarks></remarks>
    Protected Function printMarkers() As String
        Dim resultCode As String = ""
        Dim users As ArrayList = getUsers()
        Dim tempMarker As String

        Dim en As IEnumerator = users.GetEnumerator
        While en.MoveNext
            tempMarker = getMarker(en.Current(0))
            If (tempMarker.Length > 0) Then
                resultCode += "var marker" & en.Current(0) & " = new GMarker("
                resultCode += tempMarker
                resultCode += ");"
                resultCode += "GEvent.addListener(marker" & en.Current(0) & ", " & Chr(34) & "click" & Chr(34) & ", function() { marker" & en.Current(0) & ".openInfoWindowHtml(" & Chr(34) & "User <b>" & en.Current(0) & "</b> arrives here..." & Chr(34) & "); });"
                resultCode += "map.addOverlay(marker" & en.Current(0) & ");"
            End If
        End While

        Return resultCode
    End Function

    ''' <summary>
    ''' Draw the names of users and their color, on which you can click and center the map
    ''' on a specific user's actual position
    ''' </summary>
    ''' <returns>HTML code</returns>
    ''' <remarks></remarks>
    Protected Function printUserColor() As String
        Dim resultCode As String = ""
        Dim users As ArrayList = getUsers()

        Dim en As IEnumerator = users.GetEnumerator
        While en.MoveNext
            resultCode += "<div class=" & Chr(34) & "userColor" & Chr(34) & "><div style=" & Chr(34) & "background-color: " & en.Current(1) & Chr(34) & " class=" & Chr(34) & "bullet" & Chr(34) & "></div><div class=" & Chr(34) & "user" & Chr(34) & "><a href=" & Chr(34) & "javascript: map.setCenter(new GLatLng(" & getActualCoordinate(en.Current(0)) & "), 13);" & Chr(34) & ">" & en.Current(0) & "</a></div></div><br/>"
        End While

        Return resultCode
    End Function

    ''' <summary>
    ''' Adds needed code to the body element of the page to initialize the Gmap
    ''' </summary>
    ''' <param name="sender"></param>
    ''' <param name="e"></param>
    ''' <remarks></remarks>
    Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
        CType(Page.Controls(0).FindControl("body"), HtmlGenericControl).Attributes("onLoad") = "load()"
        CType(Page.Controls(0).FindControl("body"), HtmlGenericControl).Attributes("onUnLoad") = "GUnload()"
    End Sub

    ''' <summary>
    ''' To actualize the Gmap
    ''' </summary>
    ''' <param name="sender"></param>
    ''' <param name="e"></param>
    ''' <remarks></remarks>
    Protected Sub Button1_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles Button1.Click
        Response.Redirect("Default.aspx")
    End Sub
End Class
